﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using devtm.Helpers;
using System.Reflection;

namespace devtm.Editor.Configuration.formWpf
{
    public class TypeContraint
    {

        private string _Description;
        internal Type _type;
        public TypeContraint(Type type)
        {

            this._type = type;

            if (type == null)
                return;

            BaseType = type.BaseType;
            if (_type.IsGenericParameter)
                ParameterAttribute = type.GenericParameterAttributes;
            Name = type.Name;
            Interfaces = type.GetInterfaces();

  
            if (type.IsGenericParameter)
                foreach (var item in type.GetGenericParameterConstraints())
                {

                }


            if (_type.IsGenericParameter)
                _Description = type.Name;
            else
                _Description = "";


            if( type.BaseType != null && type.BaseType != typeof(object))
                _Description += " must be of type " + type.BaseType.Name;
            
            //_Description += type.BaseType.Name;

            if (Interfaces.Length > 0)
            {
                if (String.IsNullOrEmpty(_Description) || _Description == type.Name)
                    _Description = " must be ";

                foreach (Type t in Interfaces)
                    _Description += t.Name + ", ";

                _Description = _Description.Substring(0, _Description.Length - 2);
            }

            if (String.IsNullOrEmpty(_Description))
                _Description += " can be everything";

        }


        public bool IsValid(Type type)
        {

            if (_type == null)
                return true;

            if (!_type.IsGenericParameter)
                return type.IsOfType(_type);

            if (!type.IsOfType(BaseType))
                return false;

            Type[] i2 = type.GetInterfaces();
            foreach (Type i1 in Interfaces)
                if (!i2.Contains(i1))
                    return false;

            if (type.IsGenericParameter && ParameterAttribute == GenericParameterAttributes.DefaultConstructorConstraint
                && type.GenericParameterAttributes != GenericParameterAttributes.DefaultConstructorConstraint)
                    return false;

            return true;

        }


        public Type BaseType { get; private set; }
        public System.Type[] Interfaces { get; private set; }

        public GenericParameterAttributes ParameterAttribute { get; private set; }
        
        public string Name { get; private set; }
        
        public string Description
        {
            get
            {
                return _Description;
            }
        }
    }
}
